package org.six11.ss.server;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.six11.ss.server.bean.Person;
import org.six11.ss.server.bean.Room;
import org.six11.util.adt.MultiState;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class CreateAccountWebActionHandler extends WebActionHandler {

  /**
   * @param actionName
   * @param jsp
   * @param ms
   */
  public CreateAccountWebActionHandler(String actionName, String jsp, MultiState ms) {
    super(actionName, jsp, ms);
  }

  /**
   * 
   */
  @Override
  public void handle(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    String user = req.getParameter("username");
    String pass = req.getParameter("password");
    String nextJsp = jsp;
    if (user != null && pass != null) {
      // Ensure no such user exists.
      Person person = (Person) getHibernate().createQuery(
          "from Person as person where username = ?").setString(0, user).uniqueResult();
      if (person != null) {
        error(req, "There is already a player with the username '" + user + "'");
      } else if (user.length() == 0 || pass.length() == 0) {
        error(req, "The username or password field was blank.");
      } else {
        Room offline = (Room) getHibernate().load(Room.class, RoomHandler.ROOM_OFFLINE);
        Person nube = new Person();
        nube.setUsername(user);
        nube.setNick(user);
        nube.setPassword(pass);
        nube.setRoom(offline);
        getHibernate().save(nube);
        error(req, "Created player account for " + user + ".");
        req.getSession().setAttribute("userName", nube.getUsername());
        req.getSession().setAttribute("userID", "" + nube.getId());
        nextJsp = "/index.jsp";
      }
    }

    forwardTo(nextJsp, req, resp, context);

  }

}
